package org.vectrics.graphics;

import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.vectrics.SystemException;
import org.vectrics.common.graphics.Graphic;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class GraphicFileWriter {

	/**
	 * 
	 * @param client
	 * @param quality
	 * @param graphic
	 */
	public void saveImageToFile(String fileName, float quality, DynaGraphic graphic) {
		try {
			FileOutputStream fileStream = new FileOutputStream(fileName);
			this.writeGraphicAsJPEG(fileStream, quality, graphic);
		} catch (FileNotFoundException fnfe) {
			throw new SystemException("Path does not exist in order to write file: " + fileName, fnfe);
		} catch (IOException ioe) {
			throw new SystemException("IOException writing JPEG to stream", ioe);
		}
	}

	/**
	 * 
	 * @param client
	 * @param quality
	 * @param graphic
	 */
	public void saveBufferedImageToFile(String fileName, float quality, BufferedImage image) {
		try {
			FileOutputStream fileStream = new FileOutputStream(fileName);
			this.writeBufferedImageAsJPEG(fileStream, quality, image);
		} catch (FileNotFoundException fnfe) {
			throw new SystemException("Path does not exist in order to write file: " + fileName, fnfe);
		} catch (IOException ioe) {
			throw new SystemException("IOException writing JPEG to stream", ioe);
		}
	}

	
	public static void writeGraphicAsJPEG(OutputStream out, float quality,
			Graphic graphic) throws IOException {
		BufferedImage image = graphic.fill();
		writeBufferedImageAsJPEG(out, quality, image);
	}
	
	public static void writeBufferedImageAsJPEG(OutputStream out, float quality,
				BufferedImage image) throws IOException {
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image);
		param.setQuality(quality, true);
		encoder.encode(image, param);
	}
	
}
